//
//  TimingSettingsController.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/9/2.
//

import UIKit

class TimingSettingsController: UIViewController {
    
    @IBOutlet weak var brightnessSwitch: UISwitch!
    @IBOutlet weak var brightnessSlider: UISlider!
    
    var currentBrightness: CGFloat = 0
    
    private var settingBrightnessValue: CGFloat = 0
    private var tmpBrightness: CGFloat = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        overrideUserInterfaceStyle = .dark
        let value = UserDefaults.standard.float(forKey: kUserDefaults_BrightnessValue)
        settingBrightnessValue = CGFloat(value)
        tmpBrightness = CGFloat(value)
        brightnessSlider.value = Float(tmpBrightness)
        let flag = UserDefaults.standard.bool(forKey: kUserDefaults_BrightnessSwitch)
        
        brightnessSwitch.isOn = flag
        brightnessSlider.isUserInteractionEnabled = flag
        brightnessSlider.alpha = flag ? 1 : 0.5
        
        brightnessSlider.addTarget(self, action: #selector(sliderValueChange(slider:)), for: .valueChanged)
    }

    @IBAction func clickBrightnessSwitch(_ sender: UISwitch) {
        let flag = sender.isOn
        brightnessSlider.isUserInteractionEnabled = flag
        brightnessSlider.alpha = flag ? 1 : 0.5
        UserDefaults.standard.set(flag, forKey: kUserDefaults_BrightnessSwitch)
        if !flag {
            UIScreen.main.brightness = currentBrightness
        } else {
            UIScreen.main.brightness = tmpBrightness
        }
    }
    
    @objc private func sliderValueChange(slider: UISlider) {
        tmpBrightness = CGFloat(slider.value)
        UIScreen.main.brightness = tmpBrightness
        UserDefaults.standard.set(slider.value, forKey: kUserDefaults_BrightnessValue)
    }
    
}
